<?php
/**
 * 配置管理类
 * 处理系统配置的增删改查操作
 */

class ConfigManager {
    private $db;
    
    public function __construct($database) {
        $this->db = $database;
    }
    
    /**
     * 获取所有配置项
     */
    public function getAllConfigs() {
        $sql = "SELECT * FROM system_config ORDER BY config_key";
        $stmt = $this->db->query($sql);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * 根据键获取配置值
     */
    public function getConfig($key) {
        $sql = "SELECT config_value FROM system_config WHERE config_key = ?";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$key]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? $result['config_value'] : null;
    }
    
    /**
     * 设置配置项
     */
    public function setConfig($key, $value, $description = null) {
        // 检查配置项是否存在
        $existing = $this->getConfig($key);
        
        if ($existing !== null) {
            // 更新现有配置
            $sql = "UPDATE system_config SET config_value = ?, description = ? WHERE config_key = ?";
            $stmt = $this->db->prepare($sql);
            return $stmt->execute([$value, $description, $key]);
        } else {
            // 插入新配置
            $sql = "INSERT INTO system_config (config_key, config_value, description) VALUES (?, ?, ?)";
            $stmt = $this->db->prepare($sql);
            return $stmt->execute([$key, $value, $description]);
        }
    }
    
    /**
     * 删除配置项
     */
    public function deleteConfig($key) {
        $sql = "DELETE FROM system_config WHERE config_key = ?";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute([$key]);
    }
    
    /**
     * 获取工作时间配置
     */
    public function getWorkTimeConfig() {
        return [
            'work_start_time' => $this->getConfig('work_start_time') ?? '08:30',
            'work_end_time' => $this->getConfig('work_end_time') ?? '18:30',
            'lunch_start_time' => $this->getConfig('lunch_start_time') ?? '12:00',
            'lunch_end_time' => $this->getConfig('lunch_end_time') ?? '14:00',
            'work_days' => $this->getConfig('work_days') ?? '1,2,3,4,5', // 1-7 表示周一到周日
            'overtime_rate' => $this->getConfig('overtime_rate') ?? '1.5',
            'late_threshold' => $this->getConfig('late_threshold') ?? '15', // 迟到阈值（分钟）
            'early_leave_threshold' => $this->getConfig('early_leave_threshold') ?? '15' // 早退阈值（分钟）
        ];
    }
    
    /**
     * 设置工作时间配置
     */
    public function setWorkTimeConfig($configData) {
        $success = true;
        
        foreach ($configData as $key => $value) {
            if (!$this->setConfig($key, $value)) {
                $success = false;
            }
        }
        
        return $success;
    }
    
    /**
     * 获取系统信息
     */
    public function getSystemInfo() {
        // 获取数据库信息
        $sql = "SELECT 
                (SELECT COUNT(*) FROM users) as total_users,
                (SELECT COUNT(*) FROM attendance_records) as total_records,
                (SELECT COUNT(*) FROM overtime_records) as total_overtime,
                (SELECT COUNT(*) FROM leave_records) as total_leaves,
                (SELECT COUNT(*) FROM business_trips) as total_trips";
        
        $stmt = $this->db->query($sql);
        $systemInfo = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // 添加PHP和MySQL版本信息
        $systemInfo['php_version'] = PHP_VERSION;
        $systemInfo['mysql_version'] = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
        $systemInfo['server_software'] = $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown';
        
        return $systemInfo;
    }
    
    /**
     * 获取默认配置项
     */
    public function getDefaultConfigs() {
        return [
            // 工作时间配置
            'work_start_time' => [
                'value' => '08:30',
                'description' => '上班时间'
            ],
            'work_end_time' => [
                'value' => '18:30',
                'description' => '下班时间'
            ],
            'lunch_start_time' => [
                'value' => '12:00',
                'description' => '午休开始时间'
            ],
            'lunch_end_time' => [
                'value' => '14:00',
                'description' => '午休结束时间'
            ],
            'work_days' => [
                'value' => '1,2,3,4,5',
                'description' => '工作日（1-7表示周一到周日）'
            ],
            
            // 考勤规则
            'overtime_rate' => [
                'value' => '1.5',
                'description' => '加班工资倍数'
            ],
            'late_threshold' => [
                'value' => '15',
                'description' => '迟到阈值（分钟）'
            ],
            'early_leave_threshold' => [
                'value' => '15',
                'description' => '早退阈值（分钟）'
            ],
            'absent_threshold' => [
                'value' => '60',
                'description' => '缺勤阈值（分钟）'
            ],
            
            // 系统设置
            'system_name' => [
                'value' => '考勤管理系统',
                'description' => '系统名称'
            ],
            'company_name' => [
                'value' => '示例公司',
                'description' => '公司名称'
            ],
            'admin_email' => [
                'value' => 'admin@example.com',
                'description' => '管理员邮箱'
            ],
            'auto_backup' => [
                'value' => '1',
                'description' => '自动备份（1启用，0禁用）'
            ],
            'backup_interval' => [
                'value' => '7',
                'description' => '备份间隔（天）'
            ]
        ];
    }
    
    /**
     * 初始化默认配置
     */
    public function initializeDefaultConfigs() {
        $defaultConfigs = $this->getDefaultConfigs();
        $success = true;
        
        foreach ($defaultConfigs as $key => $config) {
            if (!$this->setConfig($key, $config['value'], $config['description'])) {
                $success = false;
            }
        }
        
        return $success;
    }
}
?>
